package com.yilin.gateway.filter_factory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;


public class ZuulGatewayFilterFactory extends AbstractGatewayFilterFactory<ZuulGatewayFilterFactory.Config> {
    public ZuulGatewayFilterFactory() {
        super(Config.class);
    }
    private Logger logger = LoggerFactory.getLogger(ZuulGatewayFilterFactory.class);
    private final static String GATEWAY_ZUUL = "gatewayZuul";

    /**
     */
    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            logger.info(">>>>>网关收到请求>>>>>------------------");
            logger.info("RemoteAddress:"+request.getRemoteAddress()+"------------------");
            logger.info("LocalAddress:"+request.getLocalAddress()+"------------------");
            logger.info("MethodValue:"+request.getMethodValue()+"------------------");
            logger.info("Path:"+request.getPath()+"------------------");
            logger.info("URI-Scheme:"+request.getURI().getScheme()+"------------------");
            logger.info("URI-Path:"+request.getURI().getPath()+"------------------");
            logger.info("-----------------------------");
            //#### 必须 添加网关请求头
            String scheme = request.getURI().getScheme()+"://";
            ServerHttpRequest.Builder requestBuilder = request.mutate();
            requestBuilder.header(GATEWAY_ZUUL,scheme + request.getHeaders().getFirst("host"));
            ServerHttpRequest requestNew = requestBuilder.build();
            exchange.mutate().request(requestNew).build();
            return chain.filter(exchange);
        };
    }

    /**
     * 自定义配置类
     */
    static class Config { }
}